package me.firstapp.spi.bbs.impl;

import java.util.Calendar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.bbs.SearchResult;
import me.firstapp.common.utils.ShaSign;
import me.firstapp.spi.base.impl.BaseServiceImpl;
import me.firstapp.spi.bbs.SearchService;

@Service
public class SearchServiceImpl implements SearchService {

	private Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class);

	@Value("#{configProperties['search.server.url']}")
	private String searchUrl;
	@Value("#{configProperties['search.server.key']}")
	private String searchKey;
	@Value("#{configProperties['search.server.secret']}")
	private String searchSecret;

	@Autowired
	protected RestTemplate restTemplate;

	@Override
	public SingleObject<SearchResult> search(String keyword) {
		SingleObject<SearchResult> result = new SingleObject<SearchResult>();
		try {
			Calendar calendar = Calendar.getInstance();
			ShaSign shaSign = ShaSign.getSign(searchKey, searchSecret, calendar.getTime());
			StringBuilder url = new StringBuilder(searchUrl);
			url.append("/search.do");
			url.append("?apiKey=").append(searchKey);
			url.append("&timestamp=").append(calendar.getTimeInMillis());
			url.append("&keyword=").append(keyword);

			shaSign.addParam("keyword", keyword);
			url.append("&sign=").append(shaSign.signParams());

			logger.info("调用[搜索服务]开始");
			ResponseEntity<String> responseEntity = restTemplate.exchange(url.toString(), HttpMethod.GET, null,
					String.class);
			logger.info("调用[搜索服务]结束，返回结果为:" + responseEntity.getBody());
			JSONObject resultJson = JSONObject.parseObject(responseEntity.getBody());
			if (StatusHouse.COMMON_STATUS_OK.getCode().equals(resultJson.getString("code"))) {
				JSONObject jsonObject = resultJson.getJSONObject("object");
				if (jsonObject != null) {
					SearchResult sResult = JSONObject.toJavaObject(jsonObject, SearchResult.class);
					result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
					result.setObject(sResult);
				}
			} else {
				throw new ServiceException(resultJson.getString("code"), resultJson.getString("msg"));
			}
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		return result;
	}

	@Override
	public SingleObject<Object> updateData() {
		SingleObject<Object> result = new SingleObject<Object>();
		try {
			Calendar calendar = Calendar.getInstance();
			ShaSign shaSign = ShaSign.getSign(searchKey, searchSecret, calendar.getTime());
			StringBuilder url = new StringBuilder(searchUrl);
			url.append("/updateData.do");
			url.append("?apiKey=").append(searchKey);
			url.append("&timestamp=").append(calendar.getTimeInMillis());

			url.append("&sign=").append(shaSign.signParams());

			logger.info("调用[搜索服务更新数据接口]开始");
			ResponseEntity<String> responseEntity = restTemplate.exchange(url.toString(), HttpMethod.GET, null,
					String.class);
			logger.info("调用[搜索服务更新数据接口]结束，返回结果为:" + responseEntity.getBody());
			JSONObject resultJson = JSONObject.parseObject(responseEntity.getBody());
			if (StatusHouse.COMMON_STATUS_OK.getCode().equals(resultJson.getString("code"))) {
				result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			} else {
				throw new ServiceException(resultJson.getString("code"), resultJson.getString("msg"));
			}
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		return result;
	}

}
